package com.carcenter.order.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.carcenter.common.result.Result;
import com.carcenter.common.result.enums.impl.BusinessCode;
import com.carcenter.order.entity.*;
import com.carcenter.order.service.IAppointmentDetailService;
import com.carcenter.order.service.IAppointmentMasterService;
import com.carcenter.order.service.IProductsService;
import com.carcenter.order.service.IServicesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author car
 * @since 2025-07-16
 */
@RestController
@RequestMapping("/appointment-detail")
public class AppointmentDetailController {

    @Autowired
    IAppointmentDetailService appointmentDetailService;
    @Autowired
    IAppointmentMasterService appointmentMasterService;

    @Autowired
    IProductsService productsService;
    @Autowired
    IServicesService servicesService;

    @GetMapping("/getProductServiceListByAppointmentId/{appointmentId}")
    public Result<List<AppointmentDetail>> getProductServiceListByAppointmentId(@PathVariable Integer appointmentId) {
        LambdaQueryWrapper<AppointmentDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppointmentDetail::getAppointmentId, appointmentId);
        List<AppointmentDetail> list = appointmentDetailService.list(queryWrapper);

        List<AppointmentDetail> list1 = plusProductServiceInfo(list);

        return Result.ok(list1);
    }

    public List<AppointmentDetail> plusProductServiceInfo(List<AppointmentDetail> list) {
        List<Integer> productIds = new ArrayList<>();
        List<Integer> serviceIds = new ArrayList<>();
        for (AppointmentDetail appointmentDetail : list) {
            if ("产品".equals(appointmentDetail.getItemType())) { // 用equals更规范，避免空指针
                productIds.add(appointmentDetail.getItemId());
            } else if ("服务".equals(appointmentDetail.getItemType())) { // 用else if避免重复判断
                serviceIds.add(appointmentDetail.getItemId());
            }
        }

        // 1. 处理产品：仅当productIds非空时查询
        Map<Integer, ProductDto> productDtoMap = new HashMap<>();
        if (!productIds.isEmpty()) { // 关键判断：避免空IN查询
            List<Products> products = productsService.listByIds(productIds);
            for (Products product : products) {
                ProductDto productDto = new ProductDto();
                BeanUtil.copyProperties(product, productDto);
                productDtoMap.put(product.getId(), productDto);
            }
        }

        // 2. 处理服务：仅当serviceIds非空时查询
        Map<Integer, ServiceDto> serviceDtoMap = new HashMap<>();
        if (!serviceIds.isEmpty()) { // 关键判断：避免空IN查询
            List<Services> services = servicesService.listByIds(serviceIds);
            for (Services service : services) {
                ServiceDto serviceDto = new ServiceDto();
                BeanUtil.copyProperties(service, serviceDto);
                serviceDtoMap.put(service.getId(), serviceDto);
            }
        }

        // 3. 关联DTO到详情
        for (AppointmentDetail appointmentDetail : list) {
            if ("产品".equals(appointmentDetail.getItemType())) {
                appointmentDetail.setProductDto(productDtoMap.get(appointmentDetail.getItemId()));
            } else if ("服务".equals(appointmentDetail.getItemType())) {
                appointmentDetail.setServiceDto(serviceDtoMap.get(appointmentDetail.getItemId()));
            }
        }
        return list;
    }

    @GetMapping("/getProductServiceListByStoreId/{storeId}/{month}")
    public Result<List<StoreProductDetail>> getProductServiceListByStoreId(@PathVariable Integer storeId,@PathVariable String month) {

        //生成本地时间
//        LocalDate now = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
//        String thisMonth = now.format(formatter);
        //String thisMonth = "2025年06月";

        // 解析年月字符串
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月", Locale.CHINA);
        YearMonth yearMonth = YearMonth.parse(month, formatter2);

        // 生成第一天的开始时间（例如：2025-07-01 00:00:00）
        LocalDateTime firstDayStartTime = yearMonth.atDay(1).atStartOfDay();

        // 生成最后一天的结束时间
        LocalDateTime lastDayEndTime = yearMonth.atEndOfMonth().plusDays(1).atStartOfDay();

        List<AppointmentDetail> list = appointmentDetailService.getProductServiceListByStoreId(storeId, firstDayStartTime, lastDayEndTime);

        List<AppointmentDetail> appointmentDetails = plusProductServiceInfo(list);

        Set<Integer> itemIds = appointmentDetails.stream().map(appointmentDetail -> appointmentDetail.getItemId()).collect(Collectors.toSet());

        List<StoreProductDetail> storeProductDetails = new ArrayList<>();
        for (Integer itemId : itemIds) {
            Integer monthlySales= 0;
            StoreProductDetail storeProductDetail = new StoreProductDetail();
            for (AppointmentDetail appointmentDetail : list) {
                if (appointmentDetail.getItemId()==(itemId) && appointmentDetail.getItemType().equals("产品") ) {
                    storeProductDetail.setItemId(itemId);
                    storeProductDetail.setItemType(appointmentDetail.getItemType());
                    storeProductDetail.setName(appointmentDetail.getProductDto().getProductName());
                    storeProductDetail.setRetailPrice(appointmentDetail.getProductDto().getRetailPrice());
                    storeProductDetail.setStandardPrice(appointmentDetail.getProductDto().getStandardPrice());
                    monthlySales+=1;
                }

                if (appointmentDetail.getItemId()==(itemId) && appointmentDetail.getItemType().equals("服务") ) {
                    storeProductDetail.setItemId(itemId);
                    storeProductDetail.setItemType(appointmentDetail.getItemType());
                    storeProductDetail.setName(appointmentDetail.getServiceDto().getServiceName());
                    storeProductDetail.setRetailPrice(appointmentDetail.getServiceDto().getRetailPrice());
                    storeProductDetail.setStandardPrice(appointmentDetail.getServiceDto().getStandardPrice());
                    monthlySales+=1;
                }
            }
            storeProductDetail.setMonthlySales(monthlySales);
            storeProductDetails.add(storeProductDetail);
        }

        return Result.ok(storeProductDetails);

    }


}
